<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="studentSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item >
          <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addStudent">添加学生</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="studentList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="学号"
            prop="sid"
            align="center">
        </el-table-column>
        <el-table-column
            label="姓名"
            prop="sname"
            align="center">
        </el-table-column>
        <el-table-column
            label="性别"
            prop="sex"
            align="center">
        </el-table-column>
        <el-table-column
            label="年龄"
            prop="age"
            align="center">
        </el-table-column>
        <el-table-column
            label="地址"
            prop="addr"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="班级"
            prop="cname"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="editStudent(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页导航面板-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{studentDTO}}
      <el-form :model="studentDTO" :rules="rules" ref="ruleForm">
        <el-form-item label="学生学号" prop="sid" :label-width="formLabelWidth">
          <el-input v-model="studentDTO.sid" autocomplete="off" :disabled="!addStaus"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="sname" :label-width="formLabelWidth">
          <el-input v-model="studentDTO.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="studentDTO.sex" label="男">男</el-radio>
          <el-radio v-model="studentDTO.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="studentDTO.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="studentDTO.addr" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所在班级" prop="cid" :label-width="formLabelWidth">
          <el-select v-model="studentDTO.cid" placeholder="请选择所在班级">
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStudent(addStaus)">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import studentApi from "@/api/student";
import classesApi from "@/api/classes";
export default {
  data(){
    let checkId = (rule, value, callback) =>{
      if(value === '' || value == null){
        return callback(new Error('学号不能为空'))
      }else if (value.length !== 8){
        return callback(new Error('请输入正确的学号'))
      }else{
        callback()
      }
    }
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄须为数字'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄须在1-200之间'))
      } else {
        callback()
      }
    }
    return{
      studentList: [],      // 当前页的所有学生信息集合
      page: 1,        // 当前页
      pageSize: 5,    // 每页显示记录条数
      total: 100,     // 总记录数
      studentSearch:{}, // 查询对象
      classesList:[],   // 所有班级
      dialogFormVisible:false, // 编辑学生弹窗是否可见
      addStaus:false, // 是否是编辑状态
      studentDTO:{}, // 编辑学生对象
      title: '编辑学生',
      formLabelWidth: '100px',  // 表单的标签宽度
      multipleSelection:[],     // 选中的多条记录
      sids: [],                 // 删除的学生编号数组
      //数据校验
      rules: {
        sid:[
          { validator : checkId, trigger: 'blur'}
        ],
        sname: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        age: [
          // { required: true, message: '请输入学生年龄', trigger: 'blur' },
          // 使用自定义验证规则验证年龄
          { validator : checkAge, trigger: 'blur'}
        ],
        addr: [
          {required: true, message: '请输入学生住址', trigger: 'blur'},
        ],
        cid: [
          {required: true, message: '请选择学生班级', trigger: 'blur'},
        ]
      }
    }
  },
  created() {
    this.search()
    this.findAllClasses()
  },
  methods:{
// 查询所有学生
    async findStudents(){
      const {data:res} = await studentApi.findStudents()
      if(res.code === 200){
        console.log(res.data.list)
        this.studentList = res.data.list
      }else {
        console.error("获取失败")
      }
    },
    //查询所有班级
    async findAllClasses() {
      const {data:res} = await classesApi.findAllClasses()
      console.log(res)
      if (res.code === 200) {
        this.classesList = res.data.list
      }
    },
    //分页查询
    async findByPage() {
      const {data:res} = await studentApi.findByPage(this.page,this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 条件查询带分页
    async search(){
      const {data:res} = await studentApi.search(this.page,this.pageSize,this.studentSearch)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    //添加或修改学生
    async saveStudent(edit){
      this.$refs.ruleForm.validate(async (valid) => {
        let url = "/student/add"
        let method = "post"
        if (!edit) {
          url = "/student/update"
          method = "put"
        }
        if (valid) {
          const {data: res} = await studentApi.save(url, method, this.studentDTO)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {
                this.$message.success("保存成功")
                this.dialogFormVisible = false
                this.search()
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！");
          return false;
        }
      })
    },
    // 删除学生
    async handleDelete(index, row) {
      this.sids = []
      if (row) {
        this.sids.push(row.sid)
      } else {
        this.sids = this.multipleSelection.map(item => item.sid)
      }
      this.$confirm(`是否删除学号为${this.sids}的学生吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        studentApi.deleteStudent(this.sids)
            .then(({data:res}) => {
              console.log("res:", res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({//取消后执行此操作
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    // 当pagesize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val
      this.search()
      console.log(`当前页: ${val}`);
    },
    //编辑学生
    editStudent(index, row){
      this.title = '修改学生'
      this.studentDTO = row
      this.addStaus = false
      this.dialogFormVisible = true
    },
    //添加学生
    addStudent(){
      this.title = "添加学生"
      this.studentDTO = {}
      this.addStaus = true
      this.dialogFormVisible = true
    },

  }
}
</script>
<style>
.el-card{
  width: 90%;
}
#app{
  display: flex;
  justify-content: center;
}

</style>
